<?php

namespace app\yperp\logic;

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as GuzzleHttpClient;
use think\Db as ThinkDb;

class GoodsListAsync
{
    private static $instance;
    protected $token;
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    protected $page = 1;
    protected function getGoodslist($supplierId, $limit = 10, $page = 1)
    {
        $client = new GuzzleHttpClient([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);
        // dump(['$page' => $page, '$limit' => $limit]);
        $response = $client->request('POST', 'https://gyl.scm121.com/api/goods/buyer/supplier/goods/list', [
            'json' => [
                'sort' => 'spu.SALES_VOLUME DESC,spu.ID ASC',
                'supplierId' => $supplierId,
                'asyncFillField' => true,
                'hasStock' => false,
                'itemCodeVague' => '0',
                'pageNum' => $page,
                'pageSize' => $limit,
                'styleCodeVague' => "0"

            ],
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
                'authorization' => module_config('yperp.jst_token'),
            ]
        ]);
        $data = $response->getBody()->getContents();
        $this->page++;
        $data = json_decode($data, true);
        if ($data['code'] == 1006) {
            throw new \Exception('聚水潭Token 失效：' . module_config('yperp.jst_token'));
        }
        return $data['data'];
    }
    function sync_all()
    {
        $supplierIds = ThinkDb::name('yperp_supplier_goods')->where([])->select();

        foreach ($supplierIds as $value) {
            // ['supplierId' => $items['supplierId'], 'itemSpuId' => $items['itemSpuId'], 'itemCoId' => $items['itemCoId']]
            $this->run(['supplierId' => $value['supplierId'], 'type' => 1]);
        }

    }
    function run($param)
    {

        $supplierId = $param['supplierId'];
        $noend = true;
        $page = 1;
        while ($noend) {
            $datas = $this->getGoodslist($supplierId, 35, $page);

            if (count($datas) == 0) {
                $noend = false;
            }
            $page++;
            $this->goodslist($supplierId, $datas, $param['type']);
        }
    }

    function goodslist($supplierId, $data, $type)
    {
        try {
            foreach ($data as $value) {
                $items['supplierId'] = $supplierId;
                $items['spuId'] = $value['spuId'];
                $items['itemCoId'] = $value['itemCoId'];
                $items['itemName'] = $value['itemName'];
                $items['itemSpuId'] = $value['itemSpuId'];
                $items['saleSevenDesensitized'] = $value['saleSevenDesensitized'];
                $items['saleThirtyDesensitized'] = $value['saleThirtyDesensitized'];
                $items['styleCode'] = $value['styleCode'];
                $items['supplierName'] = $value['supplierName'];
                $items['shopName'] = $value['shopName'];
                $items['brandId'] = $value['brandId'];
                $items['brandName'] = $value['brandName'];
                $items['categoryName'] = $value['categoryName'];
                $items['created'] = $value['created'];
                $items['updated'] = $value['updated'];
                // dump([$value['itemName'], $value['supplierName']]);

                $where = ['supplierId' => $items['supplierId'], 'itemSpuId' => $items['itemSpuId'], 'itemCoId' => $items['itemCoId']];
                $bool = ThinkDb::name('yperp_supplier_goods')->where($where)->column('id,async_time');

                //获取数组第一个元素
                $async_time = array_shift($bool);
                // 判断$async_time时间是否大于30天
                if (strtotime($async_time) > strtotime('-30 days') && $type == 0) {
                    dump('数据已存在，跳过');
                    continue;
                }

                dump(['itemSpuId' => $items['itemSpuId'], 'itemCoId' => $items['itemCoId']]);
                $items['async_time'] = date('Y-m-d H:i:s', time());
                if ($bool) {
                    $res = ThinkDb::name('yperp_supplier_goods')->where($where)->update($items);
                    dump('更新成功，开始详情数据获取');
                } else {
                    $res = ThinkDb::name('yperp_supplier_goods')->where($where)->insert($items);
                    dump('保存成功，开始详情数据获取');
                }

                // Queue::push(GoodsDetailAsync::class, ['itemSpuId' => $items['itemSpuId'], 'itemCoId' => $items['itemCoId']]);
                $this->goodsdetail($items['itemCoId'], $items['itemSpuId'], $supplierId);
            }
        } catch (GuzzleException $e) {
            dump($e->getMessage());
            dump($e->getTraceAsString());
        }
    }
    function goodsdetail($itemCoId, $itemSpuId, $supplierId)
    {
        $client = new GuzzleHttpClient([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);
        // dump([
        //     'itemCoId' => $itemCoId,
        //     'itemSpuId' => $itemSpuId,
        // ]);
        // try {
            $response = $client->request('POST', 'https://gyl.scm121.com/api/goods/goods/queryGoodsDetail', [
                'json' => [
                    'itemCoId' => $itemCoId,
                    'itemSpuId' => $itemSpuId,
                ],
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                    'authorization' => module_config('yperp.jst_token'),
                ]
            ]);
            $data = $response->getBody()->getContents();

            $data = json_decode($data, true);
            // dump($data);
            if ($data['success'] == true) {
                $value = $data['data'];

                $items['itemCoId'] = $itemCoId;
                $items['itemSpuId'] = $itemSpuId;

                $items['categoryId'] = $value['categoryId'];
                $items['categoryName'] = $value['categoryName'];
                $items['coId'] = $value['coId'];
                $items['created'] = $value['created'];
                $items['dealPriceNinetyMax'] = $value['dealPriceNinetyMax'];
                $items['itemCoId'] = $value['itemCoId'];
                $items['itemName'] = $value['itemName'];
                $items['itemDetailImages'] = json_encode($value['itemDetailImages'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                $items['itemMainImage'] = json_encode($value['itemMainImage'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                $items['maxCostPrice'] = $value['maxCostPrice'];
                $items['maxSupplyPrice'] = $value['maxSupplyPrice'];
                $items['minCostPrice'] = $value['minCostPrice'];
                $items['minSalesPrice'] = $value['minSalesPrice'];
                $items['minSupplyPrice'] = $value['minSupplyPrice'];
                $items['saleFifteen'] = $value['saleFifteen'];
                $items['saleFifteenDesensitized'] = $value['saleFifteenDesensitized'];
                $items['saleSeven'] = $value['saleSeven'];
                $items['saleSevenDesensitized'] = $value['saleSevenDesensitized'];
                $items['saleThirty'] = $value['saleThirty'];
                $items['saleThree'] = $value['saleThree'];
                $items['saleThreeDesensitized'] = $value['saleThreeDesensitized'];
                $items['saleYesterday'] = $value['saleYesterday'];
                $items['saleYesterdayDesensitized'] = $value['saleYesterdayDesensitized'];
                $items['salesVolume'] = $value['salesVolume'];
                $items['salesVolumeDesensitized'] = $value['salesVolumeDesensitized'];
                $items['spuId'] = $value['spuId'];
                $items['supplierId'] = $value['supplierId'];
                $items['styleCode'] = $value['styleCode'];

                $this->goodsdetailsku($value['itemSkuList'], $items, $supplierId);

                $this->AreaFreight($itemCoId, $items);

                ThinkDb::name('yperp_supplier_goods')->where(['itemSpuId' => $items['itemSpuId']])->update($items);
            }
        // } catch (\Exception $e) {
        //     dump($e->getMessage());
        //     dump($e->getTraceAsString());
        // }
    }

    function goodsdetailsku($datas, $goods, $supplierId)
    {
        foreach ($datas as $value) {

            $items['itemId'] = $value['id'];
            $items['itemCoId'] = $goods['itemCoId'];
            $items['itemSpuId'] = $goods['itemSpuId'];
            $items['itemName'] = $goods['itemName'];
            $items['coId'] = $value['coId'];
            $items['supplierId'] = $supplierId;

            $items['colour'] = $value['colour'];
            $items['costPrice'] = $value['costPrice'];
            $items['costPriceNew'] = $value['costPriceNew'];
            $items['dealPriceNinetyMax'] = $value['dealPriceNinetyMax'];
            $items['erpStyleCode'] = $value['erpStyleCode'];
            $items['itemCode'] = $value['itemCode'];
            $items['linePrice'] = $value['linePrice'];
            $items['pic'] = $value['pic'];
            $items['shortName'] = $value['shortName'];
            $items['salePrice'] = $value['salePrice'];
            $items['stock'] = $value['stock'];
            $items['stockTime'] = $value['stockTime'];
            $items['supplyPrice'] = $value['supplyPrice'];
            $items['spec'] = $value['spec'];
            $items['weight'] = $value['weight'];

            $bool = ThinkDb::name('yperp_supplier_goods_sku')->where(['itemId' => $items['itemId'], 'itemSpuId' => $items['itemSpuId']])->value('itemSpuId');
            if ($bool) {
                ThinkDb::name('yperp_supplier_goods_sku')->where(['itemSpuId' => $items['itemSpuId']])->update($items);
            } else {
                ThinkDb::name('yperp_supplier_goods_sku')->where(['itemSpuId' => $items['itemSpuId']])->insert($items);
            }
        }
    }
    function AreaFreight($supplierCoId, &$items)
    {
        $client = new GuzzleHttpClient([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);
        try {
            $response = $client->request('GET', 'https://gyl.scm121.com/api/drp/supplier/logistics/queryAreaStartFreightV2', [
                'query' => [
                    'channelCoId' => '13659884',
                    'supplierCoId' => $supplierCoId,
                ],
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                    'authorization' => module_config('yperp.jst_token'),
                ]
            ]);
            $data = $response->getBody()->getContents();
            // dump($data);
            $data = json_decode($data, true);
            if (is_array($data['data'])) {
                if ($data['data']['banArea'] !== null) {
                    $items['banArea'] = json_encode($data['data']['banArea'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
                if ($data['data']['freeArea'] !== null) {
                    $items['freeArea'] = json_encode($data['data']['freeArea'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
                if ($data['data']['normalArea'] !== null) {
                    $items['normalArea'] = json_encode($data['data']['normalArea'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
                if ($data['data']['remoteArea'] !== null) {
                    $items['remoteArea'] = json_encode($data['data']['remoteArea'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
            }
        } catch (GuzzleException $e) {
            dump($e->getMessage());
            dump($e->getTraceAsString());
        }
    }
}
